import axios from 'axios';
import { useEffect, useState, useRef } from 'react'
import { Link, useNavigate } from 'react-router-dom'
import { observer } from 'mobx-react-lite'
import { Table, Space, Card, Breadcrumb, Form, Button, Radio, DatePicker, Select,Modal, Input,message } from 'antd'
import { EditOutlined, DeleteOutlined, SearchOutlined,PlusOutlined  } from '@ant-design/icons'
import { useForm } from 'antd/lib/form/Form';
const Choose = () => {
  const [form] = useForm();
  const [data, setData] = useState([]);
  const [nodata, setnoData] = useState("1");
  const [length, setlength] = useState('');
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [editedData, setEditedData] = useState(null);
  const [params,setParams] = useState({
    page:1,
    perpage:5
  })
  const [searchInput, setSearchInput] = useState('');
  const isAlertShownRef = useRef(false);

  useEffect(() => {
    let isSubscribed = true; // 添加一个标志以跟踪组件是否仍然订阅
    axios.get('http://localhost:8000/getchoosecourselist', { params })
      .then(response => {
        if (isSubscribed) { // 在更新状态之前检查组件是否仍然订阅
          if (typeof response.data === 'string' && !isAlertShownRef.current) {
            isAlertShownRef.current = true;
            Modal.error({
              title: '非选课时间',
              content: '现在是非选课时间',
              okText: '确定',
              onOk() {
              }
            });
            setnoData("2");
          } else {
            setData(response.data.list);
            setlength(response.data.length);
            console.log("Updated data:", response.data.list);
          }
        }
      })
      .catch(error => {
        console.error('Error fetching data:', error);
      });
  
    return () => {
      isSubscribed = false; // 当组件卸载时取消订阅
    };
  }, [params]);
  
  

  // 翻页实现
  const pageChange = (page) => {
    setParams({
      ...params,
      page
    })
  }


  const onSearch = () => {
    // 发起搜索请求
    console.log(length);
    if (nodata==2) {
      
    }else{
    axios.get('http://localhost:8000/searchaddcourse', { params: { keyword: searchInput } })
      .then(response => {
        setData(response.data.results);
        setlength(response.data.length);
      })
      .catch(error => {
        console.error('Error searching data:', error);
      });}
  };

  const increase = (data) => {
    const studentid = localStorage.getItem('studentid');
    console.log(data.courseid,studentid,data.time);
    axios.post('http://localhost:8000/increasecourse', {
      courseid: data.courseid,
      studentid: studentid,
      time : data.time
    })
    .then(response => {
      // 请求成功的处理逻辑
      console.log('后端返回的数据:', response.data);
      if (response.data=="课程已添加") {
        alert('该课程已添加，无需再次选择')
      }else if (response.data=="添加成功") {
        message.success('课程添加成功')
      }else if (response.data=="课程时间冲突，是否继续添加") {
        Modal.confirm({
          title: '课程时间冲突',
          content: '课程时间冲突，是否继续添加？',
          onOk() {
            // 如果用户点击确认，执行添加成功的操作
            axios.post('http://localhost:8000/increasecourseonOk', {
              courseid: data.courseid,
              studentid: studentid,
            })
            .then(response => {
              console.log('后端返回的数据:', response.data);
              if (response.data === "添加成功") {
                message.success('课程添加成功');
              }
            })
            .catch(error => {
              // 处理请求错误的逻辑，例如显示错误提示信息
              console.error('请求失败:', error);
              message.error('课程添加失败');
            });
          },
          onCancel() {
            // 如果用户点击取消，可以选择不执行任何操作，或者根据需求处理其他逻辑
          },
        });
      }
      axios.get('http://localhost:8000/getchoosecourselist',{ params })
      .then(response => {
        console.log(response.data.list);
        setData(response.data.list);
        setlength(response.data.length);
        // 等待setData执行完毕后再打印data
        console.log("Updated data:", data);
      })
      .catch(error => {
        console.error('Error fetching data:', error);
      });
    })
    .catch(error => {
      // 请求失败的处理逻辑
      console.error('请求失败:', error);
    });
  }


  const columns = [
    {
      title: '课程编号',
      dataIndex: 'courseid',
      width: 120
    },
    {
      title: '课程',
      dataIndex: 'coursename',
    },
    {
      title: '教室',
      dataIndex: 'location'
    },
    {
      title: '开课学期',
      dataIndex: 'term'
    },
    {
      title: '上课时间',
      dataIndex: 'time'
    },
    {
      title: '课时',
      dataIndex: 'number'
    },
    {
      title: '开课学院',
      dataIndex: 'college'
    },{
      title: '属性',
      dataIndex: 'attribute'
    },
    {
      title: '最大学生数量',
      dataIndex: 'studentnum'
    },
    {
      title: '当前学生数量',
      dataIndex: 'num'
    },
    {
      title: '操作',
      render: data => {
        return (
          <Space size="middle">
            <Button
              type="primary"
              shape="circle"
              icon={<PlusOutlined />}
              onClick={() => increase(data)} 
            />
          </Space>
        )
      },
      fixed: 'right'
    }
  ]

  return (
    <div>
      <h1>Course Page</h1>
      <Card>
        <Input 
          value={searchInput} 
          onChange={(e) => setSearchInput(e.target.value)} 
          style={{ width: 200 }}
          placeholder="输入关键词"
        />
        <Button 
          type="primary" 
          icon={<SearchOutlined />} 
          onClick={onSearch}
          style={{ marginLeft: 10 }}
        >
          搜索
        </Button>
      </Card>
      <Card title={`根据筛选条件共查询到 ${length} 条结果：`}>
        <Table
          rowKey="id"
          columns={columns}
          dataSource={data}
          pagination={
            {
              pageSize: params.perpage,
              onChange: pageChange,
              current: params.page,
              total: length
            }
          }
        />
      </Card>

    </div>
  );
};


export default Choose